import os
import sys

import subprocess
from PIL import Image
import time

import chardet


def get_img_id_from_swf(extract_path, swf_file_name):
    cmd = r'{} {}'.format(extract_path, swf_file_name)

    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    out, err = p.communicate()

    id_list = []
    file_ext = None
    for line in out.splitlines():
        try:
            lin = line.decode('gbk')
        except Exception as e:
            print(e)
            lin = line.decode('utf-8')
        # print(chardet.detect(lin))
        print(lin)
        if 'JPEGs: ID(s)' in lin:
            id_list = lin.split('JPEGs: ID(s)')[1].split(',')
            file_ext = 'jpg'
        elif 'JPEG: ID(s)' in lin:
            id_list = lin.split('JPEG: ID(s)')[1].split(',')
            file_ext = 'jpg'
        # elif 'PNGs: ID(s)' in lin:
        #     id_list = lin.split('PNGs: ID(s)')[1].split(',')
        #     file_ext = 'png'
        # elif 'PNG: ID(s)' in lin:
        #     id_list = lin.split('PNG: ID(s)')[1].split(',')
        #     file_ext = 'png'

    if not id_list:
        raise Exception('提取不到swf中的图片id')

    return [id.replace(' ', '') for id in id_list], file_ext

def get_one_img_from_swf(extract_path, swf_file_name, output_dir, img_id, file_ext):

    # 如果生成之前已存在 ./output.ext扩展名 先删掉它 -------
    output_img_name = f'./output.{file_ext}'
    if os.path.exists(output_img_name):
        os.remove(output_img_name)
    # --------------------------------------------

    cmd_order = f'-{file_ext[0]}'
    cmd = r'{} {} {} {}'.format(extract_path, cmd_order, img_id, swf_file_name)
    print(cmd)
    subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    time.sleep(0.5)
    try:
        img = Image.open(output_img_name)
    except Exception as e:
        time.sleep(2)
        img = Image.open(output_img_name)
    img_path = '{}{}.{}'.format(output_dir, img_id, file_ext)
    print('当前提取图片： {}'.format(img_path))

    # 图片旋转 --------------------------------------------------
    # img = img.transpose(Image.ROTATE_270)         # 旋转 180 度角
    # img = img.transpose(Image.FLIP_LEFT_RIGHT)    # 左右对换
    # img = img.transpose(Image.FLIP_TOP_BOTTOM)      # 上下对换
    # ---------------------------------------------------------

    img.save(img_path)

def get_all_img_from_swf(extract_path, swf_file_name, output_dir):

    # 清空中间文件夹
    for name in os.listdir(output_dir):
        file_path = '{}{}'.format(output_dir, name)
        if os.path.exists(file_path):
            os.remove(file_path)

    # 获取可以获得的图片id
    id_list, file_ext = get_img_id_from_swf(extract_path, swf_file_name)
    print(f'全部图片id: {id_list}')
    print(f'图片扩展名: {file_ext}')

    # 根据图片id批量提取图片
    for id in id_list:
        get_one_img_from_swf(extract_path, swf_file_name, output_dir, id, file_ext)

    # # 清空中间图片文件
    # gbg_path = r'./output.jpg'
    # if os.path.exists(gbg_path):
    #     os.remove(gbg_path)



if __name__ == '__main__':
    # 执行文件路径
    extract_path = r'.\swfextract.exe'     # 此处一定要用反斜杠
    # swf文件路径
    swf_file_name = r'./swf/从山丹丹开花红艳艳看钢琴古筝的器乐表现特点.swf'
    output_dir = r'./img/'

    get_all_img_from_swf(extract_path, swf_file_name, output_dir)


